package com.qf.controller;

import com.qf.entity.Goods;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RequestMapping("/search")
@Controller
public class SearchController {

    @Autowired
    private RestHighLevelClient client;

    @Value("${es.index}")
    private String index;

    @Value("${es.type}")
    private String type;


    @RequestMapping("/goods")
    public String goods(String keyword, ModelMap modelMap) throws Exception {

        SearchRequest request = new SearchRequest(index);
        request.types(type);


        SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

        // 开启高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("gname", 30); // 设置高亮字段
        highlighter.preTags("<font color ='red'>");
        highlighter.postTags("</font>");

        sourceBuilder.highlighter(highlighter);


        // 判断keyword是否为空
        if (StringUtils.isEmpty(keyword)) {
            sourceBuilder.query(QueryBuilders.matchAllQuery()); // 查询全部
        } else {
            sourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "gname", "gdesc"));
        }
        request.source(sourceBuilder);
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);


        // 准备一个集合用来装所有从es查询出的数据
        List<Goods> list = new ArrayList<>();

        // 获取结果集
        SearchHit[] hits = search.getHits().getHits();
        for (int i = 0; i < hits.length; i++) {
            Map<String, Object> sourceAsMap = hits[i].getSourceAsMap();
            Goods goods = new Goods();

            // 把map中的数据拷贝到goods中
            BeanUtils.populate(goods, sourceAsMap);

            // 判断档当前doc是否存在高亮字段
            Map<String, HighlightField> highlightFields = hits[i].getHighlightFields();
            if(!highlightFields.isEmpty()){
                // 说明存在高亮字段   手机  <font>手机</font>

                // 获取高亮字段
                HighlightField gname = highlightFields.get("gname");
                Text[] fragments = gname.fragments(); // 获取高亮的内容
                System.out.println("高亮字段的数组："+Arrays.toString(fragments));
                // 覆盖掉之前的内容
                goods.setGname(fragments[0].toString());
            }
            list.add(goods);
        }

        modelMap.put("searchList", list);
        System.out.println(list);
        return "searchList";
    }
}
